package com.mashibing.juc.c_008;

import java.sql.Time;
import java.util.concurrent.TimeUnit;

/**
 * 给写方法枷锁，不给读方法加锁，容易造成脏读.
 * 造成脏读的原因是，synchronized方法和非synchronized方法可以同时运行
 * 如果业务逻辑允许脏读，则不要加锁，加锁之后程序效率低
 * @author: Yuanzt
 * @Date: 2021/3/24
 */
public class Account {

    String name;
    double balance;

    public synchronized void set(String name,double balance){
        this.name = name;
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.balance = balance;
    }

    public /*synchronized*/ double getBalance(String name){
        return this.balance;
    }

    public static void main(String[] args) {
        Account a = new Account();
        new Thread(()->a.set("zhangsan",100.00)).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(a.getBalance("zhangsan"));
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(a.getBalance("zhangsan"));

    }
}
